<?php

if (!defined('IN_SYS'))
    exit('Access Denied');

class seo_controller extends admincp {

    public function __construct() {
        parent::__construct();
    }

    public function reword() {
        if ($this->currentYumingId) {
            $yuming_id = $this->currentYumingId;
            $pg = new page("select * FROM reword where yuming_id='$yuming_id' order by id desc");
        } else {
            $pg = new page("select * FROM reword order by id desc");
        }

        $list = $pg->get_list(20);
        $page = $pg->get_page();
        require self::tpl('seo_reword');
    }

    public function reword_del() {
        $yuming_id = $this->currentYumingId;
        $id = gp('id');
        db::query("delete from reword where id='$id' and yuming_id='$yuming_id'");
        self::redirect("?m=seo&a=reword", "删除成功");
    }

    public function reword_delall() {
        db::query("delete from reword ");
        self::redirect("?m=seo&a=reword", "删除成功");
    }

    public function reword_add() {
        $yuming_id = $this->currentYumingId;
        $count = db::getField("select count(*) from reword where yuming_id='$yuming_id'");
        if (IS_POST) {
            if ($count >= 8000) {
                self::json(array('status' => 1, 'msg' => "该站点同义词已达上限！", 'redirect' => '?m=seo&a=reword'));
            }
            $msg = "";
            $v = gp('oldword,newword,type');
            $addtime = time();
            if (preg_match("#[^a-z0-9\.]#", $v['oldword']) && preg_match("#[^a-z0-9\.]#", $v['newword'])) {
                db::query("insert into reword (oldword,newword,type,yuming_id,addtime) values ('$v[oldword]','$v[newword]','$v[type]','$yuming_id','$addtime')");
                $msg = "添加成功";
            } else {
                $msg = "替换前存在非法字符";
            }
            self::json(array('status' => 1, 'msg' => "$msg", 'redirect' => '?m=seo&a=reword'));
        } else {
            if ($count >= 8000) {
                self::redirect("?m=seo&a=reword", "该站点同义词已达上限！");
            }
            require self::tpl('seo_reword_add');
        }
    }

    //导入同义词替换文件
    public function reword_upload() {

        $time = time();
        $config = array(
            "pathFormat" => "/data/temp/{time}{rand:6}",
            "maxSize" => 2048000,
            "allowFiles" => array('.txt'),
        );
        $up = new uploader('Filedata', $config, 'upload');
        $data = $up->getFileInfo();
        $yuming_id = $this->currentYumingId;
        $count = db::getField("select count(*) from reword where yuming_id='$yuming_id'");

        $file = ROOT . $data['url'];
        $content = file_get_contents($file);
        unlink($file);
        $content = iconv('gb2312', 'utf-8//IGNORE', $content);
        $array = explode("\r\n", $content);

        $insertCount = 8000 - $count;
        $insertCount = count($array) < $insertCount ? count($array) : $insertCount;
        for ($i = 0; $i < $insertCount; $i++) {
            $str_word = $array[$i];
            if (strstr($str_word, ',')) {
                $str = explode(',', $str_word);
                $r = db::find("select * from reword where oldword='$str[0]' and newword='$str[1]' and `type`=2 and yuming_id='$yuming_id'");
                if (!$r) {
                    if (preg_match("#[^a-z0-9\.]#", $str[0]) && preg_match("#[^a-z0-9\.]#", $str[1])) {
                        db::query("insert into reword(oldword,newword,`type`,addtime,yuming_id) values('$str[0]','$str[1]',2,'$time','$yuming_id')");
                    }
                }
            } elseif (strstr($str_word, '->')) {
                $str = explode('->', $str_word);
                $r = db::find("select * from reword where oldword='$str[0]' and newword='$str[1]' and `type`=1 and yuming_id='$yuming_id'");
                if (!$r) {
                    if (preg_match("#[^a-z0-9\.]#", $str[0]) && preg_match("#[^a-z0-9\.]#", $str[1])) {
                        db::query("insert into reword(oldword,newword,`type`,addtime,yuming_id) values('$str[0]','$str[1]',1,'$time','$yuming_id')");
                    }
                }
            }
        }
        echo "导入成功";
    }

    //文章标题随机插入关键词
    public function keyword() {
        $yuming_id = $this->currentYumingId;
        if (!$yuming_id) {
            self::redirect("?m=yuming&a=select");
        }
        if (IS_POST) {
            $v = gp("seoWordNum,seoWordScale,seoTitlex,seoTitle,autoseo,autonum,autokeywords,autotags,baidu_token");
            $v['seoWord'] = gp('seoWord', false);
            $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
            if ($r) {
                db::query("update seoconfig set seoWordNum='$v[seoWordNum]',seoWordScale='$v[seoWordScale]',seoTitlex='$v[seoTitlex]',seoTitle='$v[seoTitle]',seoWord='$v[seoWord]',autoseo='$v[autoseo]',autonum='$v[autonum]',autokeywords='$v[autokeywords]',autotags='$v[autotags]',baidu_token='$v[baidu_token]' where yuming_id='$yuming_id'");
            } else {
                db::query("insert into seoconfig (seoWordNum,seoWordScale,seoTitlex,seoTitle,seoWord,autoseo,autonum,yuming_id,autokeywords,autotags,baidu_token) values('$v[seoWordNum]','$v[seoWordScale]','$v[seoTitlex]','$v[seoTitle]','$v[seoWord]','$v[autoseo]','$v[autonum]','$yuming_id','$v[autokeywords]','$v[autotags]','$v[baidu_token]')");
            }
            self::json(array('status' => 1, 'msg' => '更新成功'));
        } else {
            $res = db::find("select * from seoconfig where yuming_id='$yuming_id'");
            require self::tpl("seo_keyword");
        }
    }

    //词库
    public function words() {

        $yuming_id = $this->currentYumingId;
        $stitle = gp("stitle");
        $where = array();
        $stitle = gp("stitle");
        if ($stitle) {
            $where[] = " title like '%$stitle%' ";
        }

        $where = empty($where) ? "" : "where " . join(" AND ", $where);
        $table = $this->get_tables_words($yuming_id);
        $pg = new page("select * FROM `{$table}` {$where} order by id desc");
        $list = $pg->get_list(20);
        $page = $pg->get_page();
        require self::tpl('seo_words');
    }

    //导入词库
    public function words_upload() {
        $time = time();
        $config = array(
            "pathFormat" => "/data/temp/{time}{rand:6}",
            "maxSize" => 1024 * 1024 * 1024 * 100,
            "allowFiles" => array('.txt'),
        );
        $up = new uploader('file', $config, 'upload');
        $data = $up->getFileInfo();
        if (empty($data['url'])) {
            $this->respone_json($data['state']);
        }
        $file = ROOT . $data['url'];
        $content = file_get_contents($file);
        unlink($file);
        $encode = mb_detect_encoding($content, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
        $content = mb_convert_encoding($content, 'UTF-8', $encode);
        $array = explode(",", $content);
        $result = array_chunk($array, 1000);
        if ($this->currentYumingId) {
            $yuming_id = $this->currentYumingId;
        } else {
            $yuming_id = -1;
        }
        foreach ($result as $v) {
            mredis::lPush('dokeywords_' . $yuming_id, json_encode($v));
        }
        $this->respone_json(['count' => count($array)]);
    }

    public function words_doing() {

        header('X-Accel-Buffering: no'); //关闭输出缓存
        ob_end_flush();
        ob_implicit_flush(true);
        if ($this->currentYumingId > 0) {
            $yuming_id = $this->currentYumingId;
        } else {
            $yuming_id = -1;
        }

        $hasdone = 0;
        $count = 0;
        for ($i = 0; $i <= 100; $i++) {
            $data = mredis::rPop('dokeywords_' . $yuming_id);
            if (!empty($data)) {
                $data = json_decode($data, true);
                foreach ($data as $key => $v) {
                    $v = trim($v);
                    $table = $this->get_tables_words($yuming_id);
                    try {
                        $has_data = db::find("select id from `{$table}` where `title`='" . $v . "'");
                        if (empty($has_data)) {
                            $insert_id = db::query("insert into `{$table}` (title)values('" . $v . "') ");
                            $count++;
                        }
                    } catch (Exception $ex) {
                        continue;
                    }
                }
                mac_echo("已成功处理" . $count . "条。");
            } else {
                $hasdone = 1;
                break;
            }
        }
        if ($hasdone == 1) {
            mac_echo('已全部处理完成');
            sleep(3);
            header('X-Accel-Buffering: yes'); //关闭输出缓存
            self::redirect("?m=seo&a=words");
        } else {
            mac_echo('继续进行处理');
            sleep(1);
            header('X-Accel-Buffering: yes'); //关闭输出缓存
            self::redirect("?m=seo&a=words_doing&yuming_id=$yuming_id");
        }
    }

    public function words_add() {

        if (IS_POST) {
            $msg = "";
            $v = trim(gp('title'));
            if (!empty($v)) {
                if ($this->currentYumingId > 0) {
                    $yuming_id = $this->currentYumingId;
                } else {
                    $yuming_id = -1;
                }
                $table = $this->get_tables_words($yuming_id);
                $count = db::getField("select count(*) from `{$table}` where title='$v'");
                if ($count == 0) {
                    db::query("insert into `{$table}` (title) values ('$v')");
                    $msg = "添加成功";
                } else {
                    self::json(array('status' => 0, 'errMsg' => '关键词已存在'));
                }
            } else {
                self::json(array('status' => 0, 'errMsg' => '请填写关键词'));
            }
            self::json(array('status' => 1, 'msg' => $msg, 'redirect' => '?m=seo&a=words'));
        } else {
            require self::tpl('seo_words_add');
        }
    }

    public function words_del() {
        if ($this->currentYumingId > 0) {
            $yuming_id = $this->currentYumingId;
        } else {
            $yuming_id = -1;
        }
        $table = $this->get_tables_words($yuming_id);
        $id = gp('id');
        db::query("delete from `{$table}` where id=" . $id);
        self::redirect("?m=seo&a=words", "删除成功");
    }
    
    public function words_drop() {
        if ($this->currentYumingId > 0) {
            $yuming_id = $this->currentYumingId;
        } else {
            $yuming_id = -1;
        }
        $table = $this->get_tables_words($yuming_id);
        db::query("truncate table {$table};");
        self::redirect("?m=seo&a=words", "清空成功");
    }

    //得到关键词库表
    protected function get_tables_words($yuming_id) {
        $table = "words_{$yuming_id}";
        if (!db::table_exist($table)) {
            $table = "words";
        }
        return $table;
    }

    public function exprot() {
        $data = db::select("SELECT * FROM `words` AS t1 JOIN (SELECT ROUND(RAND() * (
            (SELECT MAX(id) FROM `words`)-(SELECT MIN(id) FROM `words`))+(SELECT MIN(id) FROM `words`)) AS id) AS t2
            WHERE t1.id >= t2.id
            ORDER BY t1.id LIMIT 30000;"
        );
        shuffle($data);

        $lists = [];
        for ($i = 0; $i <= 1000; $i++) {
            $t_krr = [];
            $t_des = [];
            $t_title = array_shift($data);
            $title = $t_title['title'];
            for ($j = 0; $j <= 4; $j++) {
                $t_krr1 = array_shift($data);
                $t_krr[] = $t_krr1['title'];
            }
            for ($k = 0; $k <= 5; $k++) {
                $t_krr2 = array_shift($data);
                $t_des[] = $t_krr2['title'];
            }
            $str_keys = implode(',', $t_krr);
            $str_desc = implode(',', $t_des);
            $lists[] = ['title' => $title, 'keywords' => $str_keys, 'desc' => $str_desc];
        }
        $excel = new PHPExcel();
        $header_arr = array('A', 'B', 'C');
        $objWriter = new PHPExcel_Writer_Excel5($excel);
        $filename = 'test.xls';
        $objActSheet = $excel->getActiveSheet();
        $startRow = 1;
        foreach ($lists as $row) {
            $objActSheet->setCellValue('A' . $startRow, $row['title']);
            $objActSheet->setCellValue('B' . $startRow, $row['keywords']);
            $objActSheet->setCellValue('C' . $startRow, $row['desc']);
            $startRow++;
        }
        // 下载这个表格，在浏览器输出  
        header("Pragma: public");  
        header("Expires: 0");  
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
        header("Content-Type:application/force-download");  
        header("Content-Type:application/vnd.ms-execl");  
        header("Content-Type:application/octet-stream");  
        header("Content-Type:application/download");;  
        header('Content-Disposition:attachment;filename='.$filename.'');  
        header("Content-Transfer-Encoding:binary");  
        $objWriter->save('php://output');  

    }

}
